<?php

!defined('IN_SYSTEM') && exit('Access denied');

class class_resize_image {
    private $im = null;
    private $nh = 0;
    private $nw = 0;
    private $type = '';

    public function init($filepath) {
        $image = @getimagesize($filepath);
        
        if (!$image) return false;

        $this->type = $image['2'];

        if ($this->type == IMAGETYPE_JPEG) {
            $this->im = @imagecreatefromjpeg($filepath);
        } elseif ($this->type == IMAGETYPE_PNG) {
            $this->im = @imagecreatefrompng($filepath);
        } elseif ($this->type == IMAGETYPE_GIF) {
            $this->im = @imagecreatefromgif($filepath);
        }

        if (!$this->im) return false;

        $this->nh = imagesy($this->im);
        $this->nw = imagesx($this->im);
        return true;
    }

    public function resize($width,$height) {
        $width = $this->nw * ($width / $this->nw);
        $height = $this->nh * ($height / $this->nh);

        $new_im = imagecreatetruecolor($width,$height);
        imagecopyresampled($new_im,$this->im,0,0,0,0,$width,$height,$this->nw,$this->nh);
        $this->im = $new_im;
    }

    public function save($filepath) {
        if ($this->type == IMAGETYPE_JPEG) {
            imagejpeg($this->im,$filepath,80);
        } elseif ($this->type == IMAGETYPE_GIF) {
            imagegif($this->im,$filepath);
        } elseif($this->type == IMAGETYPE_PNG) {
            imagepng($this->im,$filepath);
        }
        $this->destroy();
        return true;
    }

    public function destroy() {
        imagedestroy($this->im);
    }
}